package com.springcloud.command;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixThreadPoolProperties;

public class CommandDemo extends HystrixCommand<String> {

    private String name;

    public CommandDemo(String name) {
        super(
                Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("Command"))
                        .andCommandPropertiesDefaults(
                                HystrixCommandProperties.defaultSetter()
                                        .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD)
//                                .withCircuitBreakerForceOpen(true)
                                .withCircuitBreakerRequestVolumeThreshold(2)
                                .withCircuitBreakerErrorThresholdPercentage(50)
                        )
                        .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.defaultSetter().withCoreSize(1)
                                .withMaximumSize(5).withAllowMaximumSizeToDivergeFromCoreSize(true))
        );
        this.name = name;
    }

    @Override
    protected String run() throws Exception {
        if(name.equals("error"))
        {
            int i=1/0;
        }
        Thread.sleep(200);
        String result = "command hello world name:"+name;
        System.err.println(result + "，currentThread："+Thread.currentThread().getName());
        return result;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

//    @Override
//    protected String getCacheKey() {
//        return name;
//    }


    @Override
    protected String getFallback() {
        return Thread.currentThread().getName()+"调用失败，默认返回";
    }
}
